import state from './state';
import util from '@/utils/util';
import sign from '@/utils/sign';

const mutations = {};

Object.keys(state).map(key => {
  mutations[`set${key.replace(/^[a-z]/i, s => s.toUpperCase())}`] = (state, value) => state[key] = value;
});

const signMutations = {};
// 加密保存的数据
[
  'userInfo',
  'wxUserInfo',
].map(k => {
  signMutations[`set${k.replace(/^[a-z]/i, s => s.toUpperCase())}`] = (state, value) => state[k] = sign.base64_encode(JSON.stringify(value));
});

Object.assign(mutations, signMutations,{
  setDicHistory(state, value) {
    if (value === true) {
      // 清除历史
      return state.dicHistory = [];
    }
    let join = true;
    let index = -1;
    let his = [...state.dicHistory];
    his.map((e, i) => {
      if (e.name === value.name && e.type === value.type) {
        // 查找数据是否已存在
        index = i;
        join = false;
      }
    });
    if (!join) {
      his.splice(index, 1); // 删除重复记录
    }
    his.push(value); //加入记录
    return state.dicHistory = his.slice(-10); // 最多保留10条记录
  },
  setUserInfo(state, value) {
    if (value.uid && Object.keys(value).length === 1) {
      util.getUserInfoApi(value.uid);
    }
    return state.userInfo = sign.base64_encode(JSON.stringify(value));
  },
});

export default mutations;
